import { ChangeEvent, useCallback, useEffect, useState } from 'react'
import { useRecoilValue } from 'recoil'
import { ReviewHooks, TableList, AreaList } from '../data'
import { isNullArray, isNullData } from '@/utils'
import { getTableList } from '../service'
import { getRoleAreaList } from '@/services/common'
import { theQuarterData } from '@/store/user'

export default (): ReviewHooks => {
  const quarterData = useRecoilValue(theQuarterData)
  // 表格数据
  const [tableList, setTableList] = useState<TableList[]>([])
  // 当前选中任务
  const [task, setTask] = useState<Array<string>>(
    isNullArray(quarterData) ? [quarterData[0].value, quarterData![0].children![0].value] : [],
  )
  // 地区
  const [areaList, setAreaList] = useState<AreaList[]>([])
  // 存放状态
  const [status, setStatus] = useState<string>('')
  // 存放选中地区
  const [area, setArea] = useState<string | number>('')
  // 存放医院名称
  const [hospitalName, setHospitalName] = useState<string>('')
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false)

  // 获取表格信息
  const getTables = async () => {
    setLoading(true)
    const res = await getTableList({
      dataReportYear: task[0] ? task[0] : '',
      dataReportQuarter: task[1] ? task[1] : '',
      status,
      // 参数在这
    })
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setTableList(res.data)
    } else {
      setTableList([])
    }
    setLoading(false)
  }

  // 获取地区
  const getAreaList = useCallback(async () => {
    const res = await getRoleAreaList()
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      const newlist = res.data.map((item) => ({ value: item.id, label: item.name }))
      setAreaList(newlist)
    } else {
      setAreaList([])
    }
  }, [])

  // 状态下拉框
  const handleStatusChange = useCallback((e: string) => {
    setStatus(e)
  }, [])

  // 任务下拉框变化时触发
  const handleTaskChange = useCallback((e: string[]) => {
    console.log('e🚀🚀🚀🚀', e)
    setTask(e)
  }, [])

  // 地区发生变化时触发
  const handleAreaChange = useCallback((e: number | string) => {
    setArea(e)
  }, [])

  // 医院名称发生变化
  const handleHospitalChange = useCallback(({ target: { value } }: ChangeEvent<HTMLInputElement>) => {
    setHospitalName(value)
  }, [])

  useEffect(() => {
    getAreaList()
  }, [])

  useEffect(() => {
    getTables()
  }, [task, area, status])

  return {
    tableList,
    task,
    areaList,
    handleStatusChange,
    handleTaskChange,
    handleAreaChange,
    status,
    hospitalName,
    area,
    getTables,
    handleHospitalChange,
    loading,
  }
}
